package online.keepon.document.controller;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import online.keepon.document.common.ErrorInfo;
import online.keepon.document.common.Result;
import online.keepon.document.util.FileUtil;
import online.keepon.document.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;

@Slf4j
@RestController
@RequestMapping(value = "/api/v1/")
public class UploadController {

    @Value("${spring.upload.path}")
    private String uploadPath;
    @Value("${spring.mvc.url}")
    private String url;

    @SneakyThrows
    @PostMapping(value = "/upload/images")
    public Result<?> upload(MultipartFile file) {
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String substring = originalFilename.substring(originalFilename.lastIndexOf('.'));
            String newName = UUIDUtil.uuid() + substring;
            LocalDate date = LocalDate.now();
            int year = date.getYear();
            int month = date.getMonthValue();
            int day = date.getDayOfMonth();
            String realPath = uploadPath + File.separator + year + File.separator + month + File.separator + day;
            FileUtil.upload(file.getBytes(), newName, uploadPath);
            return Result.ok(ErrorInfo.SUCCESS, url + newName);
        }
        return Result.fail("失败");
    }
}
